// firmorder.js  确认订单
var shihan = require('../../common/fetch')
var config = require('../../common/config')
var app = getApp()
var winScale = 750 / app.data.deviceInfo.windowWidth
var range = 794 / winScale
var invioceflag = false
var payflag = true
var payflagnum = 0
var remark = {}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    poptype: '',
    addressid: '',
    judgebupiao: '',
    judgebalance: '',
    invoiceopen: '',
    bupiao: '0',
    balance: '0',
    offlineselect: true,
    buyermessage: '',
    showLoading: true,
    bupiaoflag: false,
    balanceflag: false,
    usebalanceflag: true,
    usebupiaoflag: true,
    salesruleid: '',
    allgoodsprice: '',
    offlineflag: false,
    delete_address: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    var invoiceinfo = wx.getStorageSync('invoicekey') || {};
    // console.log(options)
    this.setData({
      buytype: options.buytype,
      teamid: options.teamid || '',
      groupbuy: options.groupbuy || '',
      originbuy: options.originbuy || '',
      productid: options.product_id || '',
      number: options.number || '',
      need: options.need || '',
      invoiceinfo: invoiceinfo
    })
    this.orderbuy()
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in-out',
    });
    this.animation = animation;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    prevPage.setData({
      is_refresh: false
    })
  },
  invoiceopen: function(e) {
    var index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: '/pages/invoice/invoice?storeid=' + e.currentTarget.dataset.id + '&invoicenote=' + this.data.orderlist.sh_invoice_label + '&type=' + JSON.stringify(this.data.orderlist.sh_sellers[index].sh_seller.sh_invoice_type) + '&salesruleid=' + this.data.salesruleid,
    })
  },
  onwriteInput: function(e) {
    this.remarkchange(e, 'add')
  },
  deleteremark: function(e) {
    this.remarkchange(e, 'del')
  },
  remarkchange: function(e, ope) {
    var selectarr = this.data.orderlist.sh_sellers
    var id = e.currentTarget.dataset.id
    if (ope == 'del') {
      remark[id] = ''
    }
    if (e.detail.value) {
      remark[id] = e.detail.value
    }
    this.setData({
      buyermessage: remark
    })
    // console.log(this.data.buyermessage)
  },
  selectoffline: function() { //选择自提
    if (this.data.offlineflag) {
      this.setData({
        offlineflag: false
      })
      this.orderbuy()
    } else {
      this.setData({
        offlineflag: true
      })
      this.orderbuy()
    }
  },
  formSubmit: function(e) {
    var that = this, formId = e.detail.formId;
    if (!this.data.offlineflag && !that.data.addressid) {
      shihan.showToast.call(that, '亲，请添加地址哦！');
      return
    }
    if (!that.data.orderlist.sh_payment_notice) {
      that.payfor(formId);
    } else {
      wx.showModal({
        title: "提醒",
        content: that.data.orderlist.sh_payment_notice,
        confirmText: "确认",
        confirmColor: "#c40000",
        showCancel: true,
        success: function(res) {
          if (res.confirm) {
            that.payfor(formId)
          }
        }
      })
    }
  },
  payfor: function(formId) {
    var data = {}
    var that = this
    var invoicearr = {}
    var selectarr = this.data.orderlist.sh_sellers
    if (this.data.offlineflag) {
      data['is_offline'] = 1
    }
    data['address_id'] = that.data.addressid //收货地址id
    data['balance'] = this.data.balance //是否使用余额1为使用
    data['bupiao'] = this.data.bupiao //是否使用红包1为使用
    if (!this.data.offlineflag) {
      for (var i = 0; i < selectarr.length; i++) {
        if (selectarr[i].sh_seller.wetherindex == true) {
          var a = selectarr[i].sh_seller.sh_id
          invoicearr[a] = this.data.invoiceinfo[a]
          invioceflag = true
        }
      }
      if (invioceflag) {
        data['invoice'] = JSON.stringify(invoicearr)
      }
    }
    payflagnum++
    // console.log(payflagnum)
    // data['invoice'] = JSON.stringify({
    //   "18":{
    //     "name_type": 0,	//发票类型：0不开，1电子，2纸质		
    //     "type": 0//发票抬头类型：0不开，1个人，2单位		
    //   }
    // })
    if (that.data.buyermessage) {
      data['remark'] = JSON.stringify(that.data.buyermessage)
    } //	{店铺id:备注内容} 订单备注
    if (that.data.buytype == 'directbuy') {
      if (that.data.groupbuy == 1) {
        data['is_group_buy'] = 1
        data['team_id'] = that.data.teamid
      }
      if (that.data.originbuy == 1) {
        data["is_original_price"] = 1
      }
      data['buy_product'] = JSON.parse('{"' + that.data.productid + '"' + ':' + that.data.number + '}')
    } else {
      data['product_id'] = that.data.productid.split(',')
    }
    if (that.data.salesruleid) {
      data['salesrule_id'] = that.data.salesruleid
    }
    // console.log(data)
    if (payflagnum == 1) {
      shihan.sendRequest(config.generate_order, 'POST', data)
        .then(function(response) {
          // console.log(response);
          if (response.data.msg == 'success') {
            payflagnum++
            that.setData({
              payment_status: response.data.data.sh_payment_status, //"unpaid" 红包不足以支付
              trade_no: response.data.data.sh_trade_no // 交易单号'T2017072519130313498'
            })
            remark = {}
            wx.removeStorageSync('invoicekey')
            wx.removeStorageSync('salesruleidkey')
            if (response.data.data.sh_payment_status == 'unpaid') {
              wx.login({
                success: function(res) {
                  shihan.sendRequest(config.get_wx_perpay, 'POST', {
                      trade_no: that.data.trade_no,
                      code: res.code
                    })
                    .then(function(response) {
                      if (response.data.code == 0) {
                        var prepayid = response.data.data.sh_package;
                        wx.requestPayment({
                          "appId": response.data.data.sh_appid,
                          'timeStamp': new String(response.data.data.sh_timestamp),
                          'nonceStr': response.data.data.sh_noncestr,
                          'package': response.data.data.sh_package,
                          'signType': 'MD5',
                          'paySign': response.data.data.sh_sign,
                          'success': function(res) {
                            app.submissionForm(prepayid.split('=')[1], '3', '4');
                            app.data.is_refresh_shopping = 1;
                            wx.redirectTo({
                              url: '/pages/paysuccess/paysuccess?tradeno=' + that.data.trade_no,
                            })
                          },
                          'fail': function(res) {
                            app.submissionForm(formId, '1', '3')
                            if (that.data.groupbuy == 1) {
                              wx.redirectTo({
                                url: '/pages/other/mygroup/mygroup?orderindex=1&floor=1',
                              })
                            } else {
                              wx.redirectTo({
                                url: '/pages/myorder/myorder?orderindex=1&floor=1',
                              })
                            }
                          }
                        })
                      }
                    }, function(error) {
                      console.log(error);
                    });
                }
              })
            } else {
              app.submissionForm(formId, '1', '3');
              app.data.is_refresh_shopping = 1;
              wx.redirectTo({
                url: '/pages/paysuccess/paysuccess?bupiao=1&tradeno=' + that.data.trade_no,
              })
            }
          } else {
            payflagnum = 0;
            shihan.showToast.call(that, response.data.msg);
          }
        }, function(error) {
          payflagnum = 0
          console.log(error);
        });
    }
  },
  selectbupiao: function(e) {
    if (this.data.orderlist.sh_bupiao > 0 && this.data.usebupiaoflag) {
      if (this.data.bupiao == '0') {
        this.setData({
          bupiao: '1',
          judgebupiao: 'select'
        })
      } else {
        this.setData({
          bupiao: '0',
          judgebupiao: ''
        })
      }
      this.confirmorderprice();
    }
  },
  selectbalance: function(e) {
    if (this.data.orderlist.sh_balance > 0 && this.data.usebalanceflag) {
      if (this.data.balance == '0') {
        this.setData({
          balance: '1',
          judgebalance: 'select'
        })
        this.confirmorderprice()
      } else {
        this.setData({
          balance: '0',
          judgebalance: ''
        })
        this.confirmorderprice();
      }
    }
  },
  selectinvioce: function(e) {
    var index = e.currentTarget.dataset.index
    var selectarr = this.data.orderlist.sh_sellers

    var invoiceinfo = wx.getStorageSync('invoicekey') || {};
    var selectarr = this.data.orderlist.sh_sellers
    // for (var i = 0; i < selectarr.length; i++) {
    var a = selectarr[index].sh_seller.sh_id
    if (invoiceinfo[a]) {
      if (selectarr[index].sh_seller.wetherindex == false) {
        selectarr[index].sh_seller.wetherindex = true
        selectarr[index].sh_seller.invoiceopen = 'select'
      } else {
        selectarr[index].sh_seller.wetherindex = false
        selectarr[index].sh_seller.invoiceopen = ''
      }
    }
    // }
    this.setData({
      orderlist: this.data.orderlist
    })
    // console.log(this.data.orderlist.sh_sellers)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var selectaddress = wx.getStorageSync('selectaddresskey');
    if (this.data.delete_address == 1) {
      this.setData({
        addressid: '',
        selectaddress: ''
      })
      this.orderbuy()
    }
    if (selectaddress) {
      this.setData({
        addressid: selectaddress.sh_id || '',
        selectaddress: selectaddress
      })
      // this.orderbuy()
    }
    if (!this.data.salesruleid) {
      var salesruleid = wx.getStorageSync('salesruleidkey');
      this.setData({
        salesruleid: salesruleid
      })
      if (this.data.hasconfirmorderprice && this.data.hasconfirmorderprice.sh_discount_total) {
        this.confirmorderprice()
      } else {
        if (selectaddress) {
          this.orderbuy()
        }
      }
    } else {
      if (selectaddress) {
        this.orderbuy()
      } else {
        if (this.data.delete_address == 0) {
          this.confirmorderprice()
        }
      }
    }
    
    if (!this.data.need) {
      this.confirmorderprice()
    }
    if (this.data.orderlist) {
      // this.orderbuy()
      this.selecthasinvioce()
    }
  },
  selecthasinvioce: function() {
    var invoiceinfo = wx.getStorageSync('invoicekey') || {};
    this.setData({
      invoiceinfo: invoiceinfo
    })
    var selectarr = this.data.orderlist.sh_sellers
    for (var i = 0; i < selectarr.length; i++) {
      var a = selectarr[i].sh_seller.sh_id
      if (this.data.invoiceinfo[a]) {
        selectarr[i].sh_seller.wetherindex = true
        selectarr[i].sh_seller.invoiceopen = 'select'
      }
    }
    this.setData({
      orderlist: this.data.orderlist
    })
  },
  openaddress: function(e) { //redirectTo
    if (!this.data.offlineflag) {
      if (this.data.addressid == undefined) {
        wx.navigateTo({
          url: '/pages/newaddress/newaddress?type=add',
        })
      } else {
        wx.navigateTo({
          url: '/pages/modaddress/modaddress?salesruleid=' + this.data.salesruleid + '&id=' + e.currentTarget.dataset.id,
        })
      }
    }
  },
  orderbuy: function() {
    var that = this,
      data = {};
    data['salesrule_id'] = that.data.salesruleid; //优惠券ID
    data['address_id'] = that.data.addressid; //地址ID
    data['is_offline'] = that.data.offlineflag ? '1' : ''; //is_offline 是否自提
    if (that.data.buytype == 'directbuy') {
      data["buy_product"] = JSON.parse('{"' + that.data.productid + '"' + ':' + that.data.number + '}')
      if (that.data.groupbuy == 1) {
        data["is_group_buy"] = '1'; //是否拼团
        data["team_id"] = that.data.teamid
      }
      if (that.data.originbuy == 1) { //是否原价购买
        data["is_original_price"] = 1
      }
    } else {
      data['product_id'] = that.data.productid.split(',');
    }
    shihan.sendRequest(config.confirm_order, 'POST', data)
      .then(function(response) {
        // console.log(response);
        if (Number(response.data.data.sh_bupiao) == 0) {
          that.setData({
            usebupiaoflag: false
          })
        }
        if (Number(response.data.data.sh_balance) == 0) {
          that.setData({
            usebalanceflag: false
          })
        }
        response.data.data.sh_sellers.forEach(function(el, index) {
          el.sh_products.forEach(function(ele, index) {
            if (!that.data.salesruleid) {
              ele.limitflag = true
            }
            if (ele.sh_label.sh_location) {
              var pos = ele.sh_label
              pos['posa'] = pos.sh_location.split('_')[0];
              pos['posb'] = pos.sh_location.split('_')[1];
            }
          })
        })
        that.setData({
          showLoading: false,
          orderlist: response.data.data,
          allgoodsprice: response.data.data.sh_pay_price,
          addressid: response.data.data.sh_address.sh_id || ''
        })
        if (!that.data.selectaddress && that.data.delete_address==0) {
          that.setData({
            selectaddress: response.data.data.sh_address
          })
        }
        that.setDefault(response.data.data);
        if (that.data.offlineselect) {
          that.setData({
            salesruleid: response.data.data.sh_salesrule.sh_default_salesrule_id || ''
          })
        }
        that.confirmorderprice()
      }, function(error) {
        console.log(error);
      });
  },
  setDefault: function(response) {
    var that = this
    if (response.sh_address.sh_province) {
      that.setData({
        addressid: response.sh_address.sh_id || ''
      })
    }
    var selectarr = that.data.orderlist.sh_sellers
    for (var i = 0; i < selectarr.length; i++) { //
      selectarr[i].sh_seller.wetherindex = false
    }
    that.selecthasinvioce()
  },
  opencoupon: function(e) {
    if (e.currentTarget.dataset.count > 0) {
      var param = '';
      var param1 = '';
      var param2 = '&productid=' + this.data.productid + '&pronum=' + this.data.number + '&addressid=' + this.data.addressid + '&balance=' + this.data.balance + '&bupiao=' + this.data.bupiao + '&salesruleid=' + this.data.salesruleid + '&isoffline=' + (this.data.offlineflag ? '1' : '');

      if (this.data.groupbuy == 1) {
        param1 = '&groupbuy=1&teamid=' + this.data.teamid
      }
      if (this.data.originbuy == 1) {
        param1 = '&originbuy=1'
      }
      if (this.data.buytype == 'directbuy') {
        param = '?type=directbuy' + param1 + param2;
      } else {
        param = '?type=shopping' + param1 + param2;
      }
      wx.navigateTo({
        url: '/pages/platformcoupon/platformcoupon' + param,
      })
    }
  },
  confirmorderprice: function() {
    var that = this
    var data = {}
    if (this.data.offlineflag) {
      data['is_offline'] = 1
    }
    if (!this.data.offlineflag) {
      data['address_id'] = that.data.addressid
    } //收货地址id
    data['balance'] = '0' //是否使用余额1为使用
    data['bupiao'] = that.data.bupiao //是否使用红包1为使用
    data['balance'] = that.data.balance //是否使用现金账户1为使用
    if (that.data.buytype == 'directbuy') {
      if (that.data.groupbuy == 1) {
        data['is_group_buy'] = 1
        data['team_id'] = that.data.teamid
      }
      if (that.data.originbuy == 1) {
        data["is_original_price"] = 1
      }
      data['buy_product'] = JSON.parse('{"' + that.data.productid + '"' + ':' + that.data.number + '}')
    } else {
      data['product_id'] = that.data.productid.split(',')
    }
    data['salesrule_id'] = that.data.salesruleid
    shihan.sendRequest(config.confirm_order_price, 'POST', data)
      .then(function(response) {
        // console.log(response);
        that.data.orderlist.sh_sellers.forEach(function(el, index) {
          el.sh_products.forEach(function(ele, index) {
            if (response.data.data.sh_salesrule_meet_pro_id) {
              response.data.data.sh_salesrule_meet_pro_id.forEach(function (elid, index) {
                if (ele.sh_id == elid) {
                  ele.limitflag = false
                }
              })
            }
          })
        })
        that.setData({
          showLoading: false,
          orderlist: that.data.orderlist,
          hasconfirmorderprice: response.data.data,
          allgoodsprice: response.data.data.sh_pay_price,
        })
        // 世瀚币，现金账户显示判断
        var use_bupiao_price = 0,
          use_balance_price = 0;
        var user_bupaio = Number(that.data.orderlist.sh_bupiao);
        var user_balance = Number(that.data.orderlist.sh_balance);
        var pay_price = response.data.data.sh_pay_price;
        if (response.data.data.sh_use_bupiao) {
          use_bupiao_price = response.data.data.sh_use_bupiao;
        }
        if (response.data.data.sh_use_balance) {
          use_balance_price = response.data.data.sh_use_balance;
        }
        if (user_bupaio > 0) {
          that.setData({
            usebupiaoflag: true
          })
        }
        if (user_balance > 0) {
          that.setData({
            usebalanceflag: true
          })
        }
        if (that.data.bupiao == '1') {
          if (use_bupiao_price >= 0 && use_balance_price == 0 && pay_price == 0) {
            that.setData({
              balance: '0',
              judgebalance: '',
              usebalanceflag: false
            })
          }
        }
        if (that.data.balance == '1') {
          if (use_balance_price >= 0 && use_bupiao_price == 0 && pay_price == 0) {
            that.setData({
              bupiao: '0',
              judgebupiao: '',
              usebupiaoflag: false
            })
          }
        }
      }, function(error) {
        console.log(error);
      });
  },
  bupiaodetail: function() { //查看红包详情
    this.setData({
      bupiaoflag: true
    })
  },
  balancedetail: function() { //查看现金账户说明
    this.setData({
      balanceflag: true
    })
  },
  closebupiao: function() {
    this.setData({
      bupiaoflag: false
    })
  },
  closebalance: function() {
    this.setData({
      balanceflag: false
    })
  },
  setModalStatus: function(e) {
    this.setData({
      poptype: e.currentTarget.dataset.type
    })
    if (e.currentTarget.dataset.status == 0) {
      this.animation.translateY(range).step();
      this.setData({
        showModalStatus: false,
        animationData: this.animation.export(),
        detailpage: true
      });
    } else {
      this.animation.translateY(-range).step();
      this.setData({
        showModalStatus: true,
        animationData: this.animation.export(),
        detailpage: false
      });
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    wx.removeStorageSync('salesruleidkey')
    wx.removeStorageSync('selectaddresskey')
    remark = {}
    payflagnum = 0
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.removeStorageSync('salesruleidkey')
    wx.removeStorageSync('selectaddresskey')
    remark = {}
    payflagnum = 0
  }
})